import 'package:flutter/material.dart';
import 'package:flutter_doban/request/request_api.dart';
import 'package:flutter_doban/models/movieitem_model.dart';
import 'movie_detail.dart';

class MovieList extends StatefulWidget {
  final String category;
  final String pageTitle;
  MovieList({Key key, this.category, this.pageTitle}) : super(key: key);

  @override
  _MovieListState createState() => _MovieListState();
}

class _MovieListState extends State<MovieList> with AutomaticKeepAliveClientMixin{

  List<MovieItemModel> movieList = List<MovieItemModel>();

  //当前的页数
  int _pageNumber = 1;
  int _pageSize = 10;
  int _total = 0;

  // 是否加载完毕了
  bool _isover = false;
  // 是否正在加载数据
  bool _isloading = true;
  ScrollController _scrollCtrl;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {

    _scrollCtrl = ScrollController();
    _scrollCtrl.addListener(() {
      //已经拉到底部了
      if(_scrollCtrl.position.pixels == _scrollCtrl.position.maxScrollExtent){
        //正在加载 或者 数据还没加载完毕 直接返回
        if(_isover || _isloading){
          return;
        }
        //数据全加载完了
        if(_pageNumber*_pageSize >= _total){
          setState(() {
            _isover = true;
          });
          return;
        }
        //页码自动增
        setState(() {
          _pageNumber++;
        });
        //再次请求数据
        getHotMovieList();
      }
    });

    //页面加载的时候先请求一次数据
    getHotMovieList();

    super.initState();
  }

  @override
  void dispose(){
    _scrollCtrl.dispose();

    super.dispose();
  }

  // 获取电影列表数据的方法
  getHotMovieList() async{
    //正在加载
    setState(() {
      _isloading = true;
    });

    var result = await RequestApi.getMovieList(widget.category, _pageNumber, _pageSize);

    List list = result.data['subjects'];
    setState(() {
       _total = result.data["total"];
      movieList.addAll(list.map((e) => MovieItemModel.fromJson(e)).toList());
      _isloading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.pageTitle),
        centerTitle: true,
      ),
      body: getMovieListWidget(),
    );
  }

  Widget getMovieListWidget(){
    return ListView.builder(
      itemCount: movieList.length,
      itemBuilder: (BuildContext ctx, int i) {
        return GestureDetector(
          onTap: () {
            Navigator.of(context)
                .push(MaterialPageRoute(builder: (BuildContext ctx) {
              return MovieDetail(
                movieId: movieList[i].id,
                title: movieList[i].title,
              );
            }));
          },
          child: Column(
            children: <Widget>[
              Divider(height: 1),
              Container(
                margin: EdgeInsets.all(5),
                height: 170,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Image.network(
                      movieList[i].images.small,
                      width: 130,
                      fit: BoxFit.cover,
                    ),
                    Expanded(child: getRightItem(i),)
                  ],
                ),
              )
            ],
          ),
        );
      },
      controller: _scrollCtrl,
    );
  }

  Widget getRightItem(int i){
    return Container(
      padding: EdgeInsets.only(left: 10),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '电影名称：${movieList[i].title}',
            style: TextStyle(fontSize: 12),
          ),
          Text('电影类型：${movieList[i].genres.join('，')}',
              style: TextStyle(fontSize: 12)),
          Text('上映年份：${movieList[i].year}年',
              style: TextStyle(fontSize: 12)),
          Text('豆瓣评分：${movieList[i].rating.average}分',
              style: TextStyle(fontSize: 12)),
          Row(
            children: <Widget>[
              Text('主演：', style: TextStyle(fontSize: 12)),
              Row(
                children: List.generate(
                    movieList[i].casts.length,
                    (int index) => Container(
                          margin: EdgeInsets.symmetric(vertical: 0, horizontal: 5),
                          child: CircleAvatar(backgroundImage: NetworkImage(
                            movieList[i].casts[index].avatars == null ? 'https://img3.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png'
                                : movieList[i].casts[index].avatars.small),
                          ),
                        )),
              )
            ],
          )
        ],
      ),
    );
  }
}
